<template>
  <div v-if="visible" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto">
      <!-- 对话框头部 -->
      <div class="p-4 border-b border-gray-200 flex justify-between items-center">
        <h3 class="text-lg font-semibold text-gray-800">{{ isEditMode ? '编辑案例' : '添加案例' }}</h3>
        <button @click="handleCancel" class="text-gray-400 hover:text-gray-500">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>

      <!-- 对话框内容 -->
      <div class="p-6">
        <FormBuilder 
          :form-title="''" 
          :fields="formFields" 
          :initial-data="initialFormData" 
          :loading="loading" 
          @submit="handleSubmit" 
          @cancel="handleCancel"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { addCase, getCaseDetail, updateCase } from '@/api/case'
import { showToast } from '@/utils/toast'
import FormBuilder from '@/components/FormBuilder.vue'

// 定义组件属性
const props = defineProps({
  caseId: {
    type: [String, Number, null],
    default: null
  }
})

// 定义事件
const emit = defineEmits(['refresh'])

// 数据
const visible = ref(false)
const loading = ref(false)
const initialFormData = ref({})
const categories = ref([
  { value: '1', label: '企业官网' },
  { value: '2', label: '电商网站' },
  { value: '3', label: '门户网站' },
  { value: '4', label: '应用程序' },
  { value: '5', label: '其他' }
])

// 计算属性
const isEditMode = computed(() => props.caseId !== null)

// 表单字段配置
const formFields = computed(() => [
  {
    name: 'title',
    label: '案例名称',
    type: 'text',
    placeholder: '请输入案例名称',
    required: true,
    rules: [
      { type: 'required', message: '案例名称不能为空' },
      { type: 'maxLength', value: 50, message: '案例名称不能超过50个字符' }
    ]
  },
  {
    name: 'categoryId',
    label: '所属分类',
    type: 'select',
    placeholder: '请选择所属分类',
    required: true,
    options: categories.value,
    rules: [
      { type: 'required', message: '所属分类不能为空' }
    ]
  },
  {
    name: 'clientName',
    label: '客户名称',
    type: 'text',
    placeholder: '请输入客户名称',
    required: true,
    rules: [
      { type: 'required', message: '客户名称不能为空' },
      { type: 'maxLength', value: 50, message: '客户名称不能超过50个字符' }
    ]
  },
  {
    name: 'description',
    label: '案例描述',
    type: 'textarea',
    placeholder: '请输入案例描述',
    rows: 4,
    required: true,
    rules: [
      { type: 'required', message: '案例描述不能为空' },
      { type: 'maxLength', value: 500, message: '案例描述不能超过500个字符' }
    ]
  },
  {
    name: 'content',
    label: '案例详情',
    type: 'textarea',
    placeholder: '请输入案例详情',
    rows: 10,
    required: true,
    rules: [
      { type: 'required', message: '案例详情不能为空' }
    ]
  },
  {
    name: 'coverImage',
    label: '封面图片',
    type: 'text',
    placeholder: '请输入封面图片URL',
    required: true,
    rules: [
      { type: 'required', message: '封面图片不能为空' },
      { type: 'url', message: '请输入有效的URL地址' }
    ]
  },
  {
    name: 'siteUrl',
    label: '案例链接',
    type: 'text',
    placeholder: '请输入案例访问链接',
    rules: [
      { type: 'url', message: '请输入有效的URL地址' }
    ]
  },
  {
    name: 'status',
    label: '状态',
    type: 'radio',
    options: [
      { value: 1, label: '已发布' },
      { value: 0, label: '草稿' }
    ],
    default: 1
  },
  {
    name: 'publishDate',
    label: '发布日期',
    type: 'date',
    required: true,
    rules: [
      { type: 'required', message: '发布日期不能为空' }
    ]
  },
  {
    name: 'seoTitle',
    label: 'SEO标题',
    type: 'text',
    placeholder: '请输入SEO标题',
    helpText: '用于搜索引擎优化的标题，建议不超过70个字符',
    rules: [
      { type: 'maxLength', value: 70, message: 'SEO标题不能超过70个字符' }
    ]
  },
  {
    name: 'seoKeywords',
    label: 'SEO关键词',
    type: 'text',
    placeholder: '请输入SEO关键词，多个关键词用逗号分隔',
    helpText: '用于搜索引擎优化的关键词'
  },
  {
    name: 'seoDescription',
    label: 'SEO描述',
    type: 'textarea',
    placeholder: '请输入SEO描述',
    rows: 3,
    helpText: '用于搜索引擎优化的描述，建议不超过160个字符',
    rules: [
      { type: 'maxLength', value: 160, message: 'SEO描述不能超过160个字符' }
    ]
  }
])

// 打开对话框
const open = async () => {
  if (isEditMode.value) {
    // 编辑模式，获取案例详情
    try {
      loading.value = true
      const response = await getCaseDetail(props.caseId)
      initialFormData.value = response
    } catch (error) {
      showToast('获取案例详情失败', 'error')
    } finally {
      loading.value = false
    }
  } else {
    // 添加模式，重置表单
    initialFormData.value = {
      status: 1,
      publishDate: new Date().toISOString().split('T')[0]
    }
  }
  visible.value = true
}

// 处理表单提交
const handleSubmit = async (formData) => {
  try {
    loading.value = true
    if (isEditMode.value) {
      await updateCase(props.caseId, formData)
      showToast('案例更新成功')
    } else {
      await addCase(formData)
      showToast('案例添加成功')
    }
    // 关闭对话框并刷新列表
    handleCancel()
    emit('refresh')
  } catch (error) {
    showToast(isEditMode.value ? '案例更新失败' : '案例添加失败', 'error')
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  visible.value = false
  // 重置表单数据
  initialFormData.value = {}
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped>
/* 自定义样式 */
</style>